package com.ourteam.workspace.api;

import java.io.File;
import java.util.Collection;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.lang.StringUtils;

import com.ourteam.scm.utils.ISCMService;
import com.ourteam.scm.utils.VersionInfo;

public class SourceCodeFileNodeBuilder extends AbstractWorkspaceResourceTreeNodeBuilder<WorkspaceResourceFileBean> {

	@Override
	public WorkspaceResourceFileBean[] getTreeNodeObjects(final WorkspaceResourceFileBean parentObject)
			throws Exception {

		Collection<File> files = FileUtils.listFiles(parentObject.getResourceFile(), new IOFileFilter() {

			@Override
			public boolean accept(File arg0, String arg1) {
				return arg0.getParentFile().equals(parentObject.getResourceFile()) && arg0.isHidden() == false;
			}

			@Override
			public boolean accept(File arg0) {
				return arg0.getParentFile().equals(parentObject.getResourceFile()) && arg0.isHidden() == false;
			}
		}, new IOFileFilter() {

			@Override
			public boolean accept(File arg0, String arg1) {
				return false;
			}

			@Override
			public boolean accept(File arg0) {
				return false;
			}
		});

		File[] fileArray = FileUtils.convertFileCollectionToFileArray(files);
		
		ISCMService iscmService = WorkspaceUtils.getSCMService(parentObject.getWorkspaceBean().getId());
		
		Map<String, VersionInfo> versionMap = iscmService.getResourceVersionInfos(getWorkspaceRootDir(),fileArray);

		WorkspaceResourceFileBean[] resourceFileBeans = new WorkspaceResourceFileBean[fileArray.length];

		for (int i = 0; i < resourceFileBeans.length; i++) {
			resourceFileBeans[i] = new WorkspaceResourceFileBean(parentObject.getWorkspaceBean(), fileArray[i]);
			if (versionMap.containsKey(fileArray[i].getName())) {
				resourceFileBeans[i].setVersionInfo(versionMap.get(fileArray[i].getName()));
			}
		}

		return resourceFileBeans;
	}

	@Override
	public WorkspaceResourceFileBean converToParentObject(Object parent) throws Exception {
		String[] ids = StringUtils.split(parent.toString(), "@");
		return new WorkspaceResourceFileBean(workspaceService.getWorkspaceById(Long.parseLong(ids[0])),
				new File(ids[1]));
	}

}
